#!/usr/bin/env python
#
# Copyright 2007 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import cgi

import gdata.service
import gdata.urlfetch
# Configure gdata python client to use app engine URL Fetch
gdata.service.http_request_handler = gdata.urlfetch

from gdata.spreadsheet.service import SpreadsheetsService

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app


class CardflasherClient(SpreadsheetsService):
  """Handle communication with the spreadsheet gdata service"""

  def  __init__(self):
    SpreadsheetsService.__init__(self)
    self.source = "markstahl-cardflasher-0.9"
    self.email = 'markstahl.api@gmail.com'
    self.password = 'testtest'
    self.ProgrammaticLogin()
    self.spreadsheet_key = 'pFTNU5W-U0barlRKCdCAaKg'
    self.worksheet_key = 'od6'

  def getAllEntries(self):
    """ Get all cards in the card stack"""
    feed = self.GetListFeed(self.spreadsheet_key, self.worksheet_key)
    return feed.entry

  def getEntry(self, url):
    """Get one card in the card stack"""
    return self.Get(url, converter=gdata.spreadsheet.SpreadsheetsListFromString)

  def updateEntry(self, url, entry):
    return self.Put(entry, url, converter=gdata.spreadsheet.SpreadsheetsListFromString)

  def insertEntry(self, row_dict):
    return self.InsertRow(row_dict, self.spreadsheet_key, self.worksheet_key)

  def deleteEntry(self, edit_url):
    return self.Delete(edit_url)


class ListCards(webapp.RequestHandler):
  def get(self):
    client = CardflasherClient()
    entries = client.getAllEntries()
    self.response.out.write("<center><h1>Flashcard List</h1>")
    self.response.out.write("<blockquote><table width='100%' border='1'>")
    for entry in entries: 
      self.response.out.write("""
          <tr align='center'>
            <td>%s</td>
            <td>%s</td>
            <td>%s</td>
          </tr>""" % (
          entry.custom["front"].text, 
          entry.custom["back"].text,
          entry.custom["score"].text))
    self.response.out.write("</table></blockquote>")


class UnknownUrl(webapp.RequestHandler):
  def get(self):
    self.redirect('/')


def main():
  application = webapp.WSGIApplication(
    [
      ('/', ListCards),
      (r'/.*', UnknownUrl),
    ],
    debug=True)
  run_wsgi_app(application)


if __name__ == '__main__':
  main()
